# -*- coding: utf-8 -*-

import fcntl
import socket
import struct

from common.channel import admin_db as channel_admin_db
from common.order import db as order_db
from common.utils import track_logging
from common.utils.exceptions import IpWhiteListsError

_LOGGER = track_logging.getLogger(__name__)


def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])


def check_valid_ip_address(ip, pay_id):
    '''
    :param ip: str(request.META['REMOTE_ADDR']) 回调请求的ip地址
    :param pay_id: data['orderid'] 回调参数中的order_id(pay_order表的id字段)
    :return: 校验失败报错
    :eg: check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    '''
    _LOGGER.info("callback ip address is: %s", ip)
    channel_id = order_db.get_pay(pay_id).channel_id
    chn = channel_admin_db.get_channel(int(channel_id))
    ip_white_list = str(chn.ip_white_list).replace(" ", "").split(',')
    if ip not in ip_white_list:
        raise IpWhiteListsError("callback ip address not in white lists!!!")
    else:
        _LOGGER.info("callback ip address check successfully!!!")


if __name__ == '__main__':
    get_ip_address('eth0')
    get_ip_address('eth1')
